/*
 * customer权限下banner编辑修改
 * @Author: zfx
 * @Date: 2018-06-19 17:53:27
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .ivu-form-item-content {
        img {
            width: 150px;
        }
    }
</style>
<template>
	<div class="v-customer-banner-edit">
		<Form
			ref="formValidate"
			:model="formValidate"
			:rules="ruleValidate"
			:label-width="labelWidth(120, 120)"
			name="create__edit">

			<Form-item
				:label="$t('banner.jump_type')"
				prop="banner_type_id">
				<Select
					v-model="formValidate.banner_type_id"
					clearable
					filterable
					name="create__banner_type_id"
					transfer>
					<Option
						v-for="(item,key) in jumpType"
						:value="String(item.id)"
						:key="key">{{ item.name }}</Option>
				</Select>
			</Form-item>

			<Form-item
				v-if="formValidate.banner_type_id == '2'"
				:label="$t('banner.product_information')"
				prop="product_information">
				<Row>
					<i-col span="22">
						<Select
							v-model="formValidate.product_information"
							name="create__product_information"
							clearable
							transfer>
							<Option
								v-for="(item,key) in products"
								:value="item.spu_code.replace(/(^\s*)|(\s*$)/g, '')"
								:key="key">{{ item.name }}</Option>
						</Select>
					</i-col>
					<i-col
						:offset="1"
						span="1">
						<Tooltip
							:content="$t('banner.jump_info')"
							placement="left">
							<a class="help">
								<Icon
									type="help-circled"
									size="20"/>
							</a>
						</Tooltip>
					</i-col>
				</Row>
			</Form-item>

			<Form-item
				:label="$t('banner.specified_type')"
				prop="type">
				<Select
					v-model="formValidate.type"
					name="create__specified_type"
					transfer>
					<Option
						v-for="(item,key) in specified_data"
						:value="item.value"
						:key="key">{{ item.name }}</Option>
				</Select>
			</Form-item>

			<Form-item
				v-if="formValidate.type == 'Store'"
				:label="$t('banner.store')"
				prop="store">
				<Select
					v-model="formValidate.store"
					multiple
					clearable
					name="create__store"
					transfer>
					<Option
						v-for="(item,key) in storesData"
						:value="String(item.id)"
						:key="key">{{ item.name }}</Option>
				</Select>
			</Form-item>

			<Form-item
				v-else-if="formValidate.type == 'DeviceAccount'"
				:label="$t('banner.device_number')"
				prop="device_number">
				<Select
					v-model="formValidate.device_number"
					multiple
					clearable
					name="create__device_name"
					transfer>
					<OptionGroup
						v-for="(item,key) in storesData"
						:key="key"
						:label="item.name">
						<Option
							v-for="(value,key) in item.get_device_accounts"
							:value="String(value.id)"
							:key="key">{{ value.account }}</Option>
					</OptionGroup>
				</Select>
			</Form-item>

			<Form-item
				:label="$t('banner.name')"
				prop="name">
				<i-input
					v-model="formValidate.name"
					:placeholder="$t('banner.please_enter_name')"
					name="create__name"
					type="text"/>
			</Form-item>

			<Form-item
				:label="$t('banner.priority')"
				prop="priority">
				<InputNumber
					:min="0"
					:max="100000"
					v-model="formValidate.priority"
					name="create__priority"/>
			</Form-item>

			<Form-item
				:label="$t('banner.thumb')"
				prop="thumb">
				<Uploader
					ref="uploader"
					:default.sync="thumb_src"
					@on-remove="handleRemove"
					@on-change="handleChange">
					{{ $t('banner.thumb_tip') }}
				</Uploader>
			</Form-item>

			<Form-item
				:label="$t('common.start_time')"
				prop="thumb">
				<DatePicker
					:placeholder="$t('common.please_select',{'field':$t('common.start_time')})"
					:value="formValidate.started_at"
					name="start_time"
					type="datetime"
					placement="bottom-start"
					format="yyyy-MM-dd HH:mm:ss"
					split-panels
					@on-change="changeStartTime"/>
			</Form-item>

			<Form-item
				:label="$t('common.end_time')"
				prop="thumb">
				<DatePicker
					:placeholder="$t('common.please_select',{'field':$t('common.end_time')})"
					:value="formValidate.ended_at"
					name="end_time"
					type="datetime"
					placement="bottom-start"
					format="yyyy-MM-dd HH:mm:ss"
					split-panels
					@on-change="changeEndTime"/>
			</Form-item>

			<Form-item>
				<Button
					type="primary"
					name="create__submit"
					@click="handleSubmit('formValidate')">
					{{ $t('common.update') }}
				</Button>
			</Form-item>

		</Form>
	</div>
</template>

<script>

import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { validateUpdateImage } from 'src/validate'; // 引入校验文件
import Uploader from 'src/views/component/Uploader';

export default {

	name: 'BannerEdit',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],
	props: {
		jumpType: {
			type: Array,
			default() {
				return [];
			},
		},
		storesData: {
			type: Array,
			default() {
				return [];
			},
		},
		deviceAccounts: {
			type: Array,
			default() {
				return [];
			},
		},
		products: {
			type: Array,
			default() {
				return [];
			},
		},
		bannerDetail: {
			type: Object,
			default() {
				return {};
			},
		},
		loading: {
			type: Boolean,
			default() {
				return false;
			},
		},
	},

	data() {
		return {
			specified_data: [
				{
					name: this.$t('banner.device_number'), // 设备账号
					value: 'DeviceAccount',
				},
				{
					name: this.$t('banner.store'), // 店铺
					value: 'Store',
				},
			],

			formValidate: {
				banner_type_id: '', // 跳转类型
				product_information: '', // 商品信息
				type: '', // 指定设备类型
				store: [], // 店铺
				device_number: [], // 设备编号
				name: '', // banner名称
				priority: 0, // 优先级
				thumb: '', // banner图
				started_at: '',	// 生效时间
				ended_at: '',	// 失效时间
			}, // 更新产banner时的表单

			ruleValidate: { // 表单验证规则
				banner_type_id: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('banner.jump_type') }),
						trigger: 'blur,change',
					},
				],
				product_information: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('banner.product_information') }),
						trigger: 'blur,change',
					},
				],
				type: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('banner.specified_type') }),
						trigger: 'blur,change',
					},
				],
				store: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('banner.store') }),
						trigger: 'blur,change',
					},
				],
				device_number: [
					{
						required: true,
						type: 'array',
						message: this.$t('validate.required', { field: this.$t('banner.device_number') }),
						trigger: 'blur,change',
					},
				],
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('banner.name') }),
						trigger: 'blur,change',
					},
				],
				priority: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('banner.priority') }),
						trigger: 'blur,change',
					},
				],
				thumb: [
					{ required: true, validator: validateUpdateImage, trigger: 'blur,change' },
				],
			},

			// 上传的图片信息
			thumb_src: '',
		};
	},
	created() {
		this.initFormData();
	},
	methods: {
		initFormData() {
			if (this.bannerDetail) {
				this.formValidate.banner_type_id = String(this.bannerDetail.banner_type_id);
				this.formValidate.product_information = this.bannerDetail.data || '';

				this.formValidate.type = this.bannerDetail.get_stores.length > 0 ? 'Store' : 'DeviceAccount';
				this.formValidate.store = this.bannerDetail.get_stores.length > 0 ? this.bannerDetail.get_stores.map(tag => String(tag.id)) : [];
				this.formValidate.device_number = this.bannerDetail.get_device_accounts.length > 0 ? this.bannerDetail.get_device_accounts.map(tag => String(tag.id)) : [];

				this.formValidate.name = this.bannerDetail.name;
				this.formValidate.priority = parseInt(this.bannerDetail.priority, 10);

				// this.formValidate.thumb = this.bannerDetail.image;
				this.thumb_src = this.bannerDetail.image;

				this.formValidate.started_at = this.bannerDetail.started_at;
				this.formValidate.ended_at = this.bannerDetail.ended_at;
			}
		},

		/**
		 * 改变生效时间之后触发的回调
		 * @param  {string} date {改变的时间}
		 * @return {undefined}
		 */
		changeStartTime(date) {
			this.formValidate.started_at = date;
		},

		/**
		 * 改变失效时间之后触发的回调
		 * @param  {string} date {改变的时间}
		 * @return {undefined}
		 */
		changeEndTime(date) {
			this.formValidate.ended_at = date;
		},

		/**
		 * 删除图片
		 * @return {undefined}
		 */
		handleRemove() {
			this.formValidate.thumb = null;
			// this.$refs.formValidate.validateField('thumb');
		},

		/**
		 * 选择图片
		 * @param {Object} file {选择的文件对象集合}
		 * @return {undefined}
		 */
		handleChange({ file }) {
			this.formValidate.thumb = file;
			// this.$refs.formValidate.validateField('thumb');
		},

		/**
         * 更新Banner信息
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			if (this.loading) return;
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.$emit('update', this.bannerDetail.id, this.formDataCreate());
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 手动拼接表单数据
         * @return {Object} {拼接好的表单数据}
         */
		formDataCreate() {
			const new_object = {
				_method: 'PUT',

				banner_type_id: this.formValidate.banner_type_id, // 跳转类型
				type: this.formValidate.type, // 指定设备类型
				name: this.formValidate.name, // banner名称
				priority: this.formValidate.priority, // 优先级
				image: this.formValidate.thumb, // banner图

				started_at: this.formValidate.started_at, // 生效时间
				ended_at: this.formValidate.ended_at, // 失效时间

				data: this.formValidate.product_information, // 商品信息
			};

			switch (this.formValidate.type) {
			case 'DeviceAccount':
				new_object.values = this.formValidate.device_number;

				break;
			case 'Store':
				new_object.values = this.formValidate.store;

				break;
			default:
				break;
			}
			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				switch (key) {
				case 'values':

					new_object[key].forEach((tag, index) => {
						form_data.append(`${key}[${index}]`, tag);
					});

					break;

				default:

					form_data.append(key, new_object[key]);

					break;
				}
			});
			return form_data;
		},

	},
};
</script>
